import streamlit as st
import pandas as pd
from datetime import datetime, timedelta
from typing import Dict, Any

class ResultsView:
    """结果查看视图类"""
    
    def __init__(self):
        pass
    @classmethod
    def set_email_controller(cls, email_controller):
        cls.email_controller = email_controller
    def render(self):
        """优化的渲染结果查询页面"""
        st.markdown("<h1 class='main-header'>邮件处理结果查询</h1>", unsafe_allow_html=True)
        
        # 初始化session state
        if 'results_page' not in st.session_state:
            st.session_state.results_page = 1
        if 'results_search_conditions' not in st.session_state:
            st.session_state.results_search_conditions = {}
        
        # 搜索功能（添加防抖）
        with st.form("search_form"):
            st.subheader("搜索条件")
            search_cols = st.columns([1, 1, 1, 1])
            
            with search_cols[0]:
                search_subject = st.text_input("邮件主题", 
                                             value=st.session_state.results_search_conditions.get('subject', ''),
                                             placeholder="输入邮件主题关键词")
            with search_cols[1]:
                search_uid = st.text_input("邮件UID", 
                                         value=st.session_state.results_search_conditions.get('uid', ''),
                                         placeholder="输入邮件UID")
            with search_cols[2]:
                search_consignment_no = st.text_input("委托单号", 
                                                    value=st.session_state.results_search_conditions.get('consignment_no', ''),
                                                    placeholder="输入委托单号")
            with search_cols[3]:
                st.write("")
                search_button = st.form_submit_button("🔍 搜索", use_container_width=True)
            
            # 处理搜索
            if search_button:
                st.session_state.results_search_conditions = {
                    '邮件主题': search_subject,
                    'UID': search_uid,
                    '委托单号': search_consignment_no
                }
                st.session_state.results_page = 1  # 重置到第一页
                st.cache_data.clear()  # 清除缓存
                st.rerun()
            
        # 查询数据（使用缓存）
        query_result = self.email_controller.query_emails_with_pagination_cached(
            page=st.session_state.results_page,
            page_size=20,
            search_conditions=st.session_state.results_search_conditions
        )
        # 更新临时总数, 防止因缓存问题导致的分页查询结果——总记录数的不一致，导致前端显示不一致
        st.session_state.results_temp_total = max(query_result['total_count'], st.session_state.results_temp_total)
        # 显示查询结果
        self._render_results(query_result)
    
    def _get_session_data(self) -> Dict[str, Any]:
        """从session_state获取数据（兼容旧版本）"""
        email_data = st.session_state.get('email_data', [])
        
        # 应用搜索过滤
        filtered_data = email_data
        search_conditions = st.session_state.results_search_conditions
        
        if any(search_conditions.values()):
            filtered_data = []
            for record in email_data:
                match = True
                if search_conditions.get('subject') and search_conditions['subject'].strip():
                    if search_conditions['subject'].lower() not in str(record.get('邮件主题', '')).lower():
                        match = False
                if search_conditions.get('uid') and search_conditions['uid'].strip():
                    if search_conditions['uid'].lower() not in str(record.get('UID', '')).lower():
                        match = False
                if search_conditions.get('consignment_no') and search_conditions['consignment_no'].strip():
                    if search_conditions['consignment_no'].lower() not in str(record.get('委托单号', '')).lower():
                        match = False
                if match:
                    filtered_data.append(record)
        
        # 分页处理
        page_size = 20
        start_idx = (st.session_state.results_page - 1) * page_size
        end_idx = start_idx + page_size
        page_data = filtered_data[start_idx:end_idx]
        
        total_count = len(filtered_data)
        total_pages = (total_count + page_size - 1) // page_size
        
        return {
            'data': page_data,
            'total_count': total_count,
            'total_pages': total_pages,
            'current_page': st.session_state.results_page,
            'page_size': page_size,
            'has_next': st.session_state.results_page < total_pages,
            'has_prev': st.session_state.results_page > 1
        }
    
    def _render_results(self, query_result: Dict[str, Any]):
        """优化的渲染查询结果"""
        st.subheader("查询结果")
        
        # 显示统计信息和分页信息
        info_cols = st.columns([1, 1, 1, 2])

        with info_cols[0]:
            st.metric("总记录数", st.session_state.results_temp_total)
        with info_cols[1]:
            total_pages = query_result['total_pages']
            st.metric("当前页", f"{query_result['current_page']}/{total_pages if total_pages != 0 else 1}")
        with info_cols[2]:
            st.metric("本页记录", len(query_result['data']))
        with info_cols[3]:
            # 页码选择下拉框
            if query_result['total_pages'] > 1:
                page_options = list(range(1, query_result['total_pages'] + 1))
                selected_page = st.selectbox(
                    "跳转到页码",
                    options=page_options,
                    index=query_result['current_page'] - 1,  # 当前页索引
                    key="page_selector"
                )
                
                # 如果选择的页码与当前页不同，则跳转
                if selected_page != query_result['current_page']:
                    st.session_state.results_page = selected_page
                    st.rerun()
            else:
                st.write("仅有1页数据")
        
        # 显示数据表格
        if query_result['data']:
            # 限制显示的列数，避免渲染过多列
            display_columns = ['UID', '邮件主题', '委托单号', '处理状态', '最新识别时间']
            
            email_df = pd.DataFrame(query_result['data'])
            
            # 只显示关键列
            available_columns = [col for col in display_columns if col in email_df.columns]
            if available_columns:
                display_df = email_df[available_columns]
            else:
                display_df = email_df
            
            # 使用更高效的显示方式
            st.dataframe(
                display_df, 
                use_container_width=True, 
                height=300,  # 减少高度
                hide_index=True
            )
            
            # 邮件详情查看（延迟加载）
            self._render_email_detail_lazy(query_result['data'])
        else:
            st.info("暂无符合条件的邮件数据")
    
    def _render_email_detail_lazy(self, email_data: list):
        """延迟加载邮件详情"""
        if not email_data:
            return
            
        # 直接显示邮件详情选择，不使用expander
        st.subheader("📧 邮件详情")
        
        # 获取UID列表
        uid_options = ["选择..."] + [str(record.get('UID', '')) for record in email_data if record.get('UID')]
        selected_uid = st.selectbox("选择邮件UID查看详情", options=uid_options, key="email_detail_selector")
        
        if selected_uid != "选择...":
            # 从当前页数据中查找，避免额外查询
            selected_email = None
            for record in email_data:
                if str(record.get('UID', '')) == selected_uid:
                    selected_email = record
                    break
            
            if selected_email:
                self._display_email_detail(selected_email)
            else:
                st.warning("未找到对应的邮件详情数据")
    
    def _display_email_detail(self, selected_email: Dict[str, Any]):
        """显示邮件详情"""
        st.write("**邮件完整信息:**")
        
        # 分两列显示基本信息和其他字段
        col1, col2 = st.columns(2)
        
        # 定义重要字段优先显示在左列
        priority_fields = ['UID', '委托单号', '邮件主题', '邮件发件人', '邮件发送时间', '邮件正文', '邮件附件', '邮件附件数量' '最新识别时间', '处理状态']
        
        with col1:
            st.write("**邮件信息:**")
            for field in priority_fields:
                if field in selected_email:
                    value = selected_email[field]
                    st.write(f"**{field}:** {value}")
        
        with col2:
            st.write("**结果字段:**")
            for key, value in selected_email.items():
                if key not in priority_fields:
                    # 如果值太长，使用文本区域显示
                    if isinstance(value, str) and len(str(value)) > 100:
                        st.write(f"**{key}:**")
                        st.text_area(f"{key}_detail", value, height=100, disabled=True, key=f"email_detail_{key}_{selected_email.get('UID', 'unknown')}")
                    else:
                        st.write(f"**{key}:** {value}")
        
        # 显示处理结果（如果存在且内容较长）
        if '最新识别结果' in selected_email:
            result = selected_email['最新识别结果']
            if result and len(str(result)) > 50:
                st.write("**详细处理结果:**")
                st.text_area("识别结果详情", result, height=200, disabled=True, key=f"email_result_detail_{selected_email.get('UID', 'unknown')}")
        
        # 显示完整的JSON数据
        st.write("**完整数据 (JSON格式):**")
        st.json(selected_email)
